from socket import *
import threading

socket = socket()

ip = gethostname()
port = 8080

socket.bind((ip, port))

socket.listen()

uname_list = []
socket_list = []


def forwar_msgd(s, uname):
    while True:
        try:
            content = s.recv(2048).decode('utf-8')
            print(f'{uname} 说：{content}')
            for sl in socket_list:
                sl.send(f'{uname} 说：{content}'.encode('utf-8'))
        except:
            print(f'{uname} 退出聊天室')
            socket_list.remove(s)
            uname_list.remove(uname)
            for sl in socket_list:
                sl.send(f'{uname} 退出聊天室'.encode('utf-8'))
            # for ul,sl in zip(uname_list, socket_list):
            #     print(ul, sl)
            break



while True:
    s, addr = socket.accept()
    socket_list.append(s)
    uname = s.recv(1024).decode('utf-8')
    uname_list.append(uname)
    print(uname, addr)

    for sl in socket_list:
        sl.send(f'【系统消息】： {uname}加入聊天室'.encode('utf-8'))

    threading.Thread(target=forwar_msgd, args=(s, uname, )).start()



    # 测试
    # for ul, sl in zip(uname_list, socket_list):
    #     print(ul, sl)




















































